from flask import Flask
import os
from config import Config
from extensions import db, login_manager, migrate, assets
from create_images import create_default_images

def create_app(config_class=Config):
    app = Flask(__name__, 
                static_folder='static',  # 确保这里正确设置
                template_folder='templates')  # 确保这里正确设置
    app.config.from_object(config_class)
    
    # 添加调试信息
    @app.context_processor
    def inject_debug():
        return dict(debug=app.debug)
    
    # 确保上传文件夹存在
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    
    # 确保默认图片目录存在
    os.makedirs(os.path.join(app.static_folder, 'img'), exist_ok=True)
    
    # 创建默认图片
    try:
        create_default_images()
    except Exception as e:
        print(f"创建默认图片时出错: {e}")
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)
    assets.init_app(app)
    
    with app.app_context():
        # 导入模型
        from models import User, Coach, Course, Booking, Activity, Post
        
        # 注册蓝图
        from routes import main_bp
        app.register_blueprint(main_bp)
        
        # 确保数据库表已创建
        db.create_all()
    
    return app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True) 